package com.rizzo.web.validator;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author Jan Lievens
 */
public class EmailValidator implements Validator {

    /**
     * Method validate ...
     *
     * @param facesContext of type FacesContext
     * @param uiComponent  of type UIComponent
     * @param object       of type Object
     * @throws ValidatorException when
     */
    public void validate(FacesContext facesContext, UIComponent uiComponent, Object object) throws ValidatorException {
        String enteredEmail = (String) object;
        //Set the email pattern string
        Pattern p = Pattern.compile(".+@.+\\.[a-z]+");
        //Match the given string with the pattern
        Matcher m = p.matcher(enteredEmail);
        //Check whether match is found
        boolean matchFound = m.matches();
        if (!matchFound) {
            FacesMessage message = new FacesMessage();
            message.setDetail("Email not valid");
            message.setSummary("Email not valid");
            message.setSeverity(FacesMessage.SEVERITY_ERROR);
            throw new ValidatorException(message);
        }

    }
}
